package com.sunwayworld.basemodule.rm.archivesmanage.io;

import com.sunwayworld.baseline.framework.override.LimsExcelHelper;
import com.sunwayworld.basemodule.rm.archivesmanage.bean.LimsArchivesManageBean;
import com.sunwayworld.basemodule.rm.archivesmanage.service.LimsArchivesManageService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.io.file.FilePathDTO;
import com.sunwayworld.framework.io.file.FilePathManager;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.BeanUtils;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.module.item.file.bean.CoreFileBean;
import com.sunwayworld.module.item.file.bean.CoreFileImportResultDTO;
import com.sunwayworld.module.item.file.function.CoreFileImportFunction;
import com.sunwayworld.module.item.file.utils.CoreFileUtils;
import com.sunwayworld.module.sys.code.bean.CoreCodeBean;
import com.sunwayworld.module.sys.code.service.CoreCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@GikamBean
@Component(value = "LimsArchivesImportFileFunction")
public class LimsArchivesImportFileFunction implements CoreFileImportFunction {

    @Autowired
    @Lazy
    private CoreCodeService coreCodeService;

    @Autowired
    @Lazy
    private LimsArchivesManageService limsArchivesManageService;

    @Override
    public CoreFileImportResultDTO apply(CoreFileBean coreFileBean) {
        CoreFileImportResultDTO resultDTO = new CoreFileImportResultDTO();
        List<LimsArchivesManageBean> archivesManagerBeans = LimsExcelHelper.readDataFromExcel(FilePathManager.getLocalPath(CoreFileUtils.toFilePath(coreFileBean)).toString(), 0, 1, LimsArchivesManageBean.class);
        if (archivesManagerBeans.isEmpty()) {
            throw new InvalidDataException("导入失败！");
        }
        List<String> columns = Arrays.asList("archivesCode", "archivesName", "archivesType");
        List<String> colNames = Arrays.asList("【档案编号】", "【档案名称】", "【档案类型】");
        archivesManagerBeans.forEach(a -> {
            StringBuilder msg = new StringBuilder();
            for (int i = 0; i < columns.size(); i++) {
                Object value = BeanUtils.getPropertyValue(a, columns.get(i));
                if (value == null || (value.getClass().equals(String.class) && value.equals(""))) {
                    msg.append(colNames.get(i));
                }
            }
            if (msg.length() > 0) {
                msg.append(" 为必填项；");
            }
            if (msg.length() > 0) {
                if (!StringUtils.isBlank(a.getExt$Item("validateimpmsg"))) {
                    a.setExt$Item("validateimpmsg", a.getExt$Item("validateimpmsg").concat(msg.toString()));
                } else {
                    a.setExt$Item("validateimpmsg", msg.toString());
                }
            }
        });
        // 校验是否存在重复档案编号
        Map<String, List<LimsArchivesManageBean>> groupByCode = archivesManagerBeans.stream().filter(a -> !StringUtils.isBlank(a.getArchivesCode())).collect(Collectors.groupingBy(LimsArchivesManageBean::getArchivesCode));
        groupByCode.forEach((c, temp) -> {
            if (temp.size() > 1) {
                temp.forEach(a -> {
                    if (!StringUtils.isBlank(a.getExt$Item("validateimpmsg"))) {
                        a.setExt$Item("validateimpmsg", a.getExt$Item("validateimpmsg").concat("表格中字段【档案编号】存在重复；"));
                    } else {
                        a.setExt$Item("validateimpmsg", "表格中字段【档案编号】存在重复；");
                    }
                });
            }
        });
        List<LimsArchivesManageBean> exists = limsArchivesManageService.selectListByFilter(SearchFilter.instance().match("archivesCode", new ArrayList<>(groupByCode.keySet())).filter(MatchPattern.OR));
        if (!exists.isEmpty()) {
            exists.forEach(e -> {
                List<LimsArchivesManageBean> temp = groupByCode.get(e.getArchivesCode());
                if (temp != null && !temp.isEmpty()) {
                    temp.forEach(a -> {
                        if (!StringUtils.isBlank(a.getExt$Item("validateimpmsg"))) {
                            a.setExt$Item("validateimpmsg", a.getExt$Item("validateimpmsg").concat("【档案编号】重复导入；"));
                        } else {
                            a.setExt$Item("validateimpmsg", "【档案编号】重复导入；");
                        }
                    });
                }
            });
        }

        // 返还校验结果
        if (archivesManagerBeans.stream().anyMatch(i -> !StringUtils.isEmpty(i.getExt$Item("validateimpmsg")))) {
            FilePathDTO fr = CoreFileUtils.toFilePath(coreFileBean);
            FilePathDTO filePathDTO = LimsExcelHelper.writeImportFailureListAsExcel(FilePathManager.getLocalPath(fr).toString(), archivesManagerBeans, 0, 1, "导入错误信息.xlsx", false);
            resultDTO.setUrl(FilePathManager.getUrl(filePathDTO));
            resultDTO.setMessage("导入失败");
            return resultDTO;
        }

        List<CoreCodeBean> archivesTypes = coreCodeService.selectListByFilter(SearchFilter.instance().match("codeCategoryId", "archivesType").filter(MatchPattern.EQ));

        List<Long> ids = ApplicationContextHelper.getNextIdentityList(archivesManagerBeans.size());
        archivesManagerBeans.forEach(smb -> {
            smb.setId(ids.remove(0));
            Optional<CoreCodeBean> archivesType = archivesTypes.stream().filter(c -> c.getCodeName().equals(smb.getArchivesType())).findAny();
            if (archivesType.isPresent()) {
                smb.setArchivesType(archivesType.get().getCode());
            } else {
                smb.setArchivesType("");
            }
        });
        limsArchivesManageService.getDao().insert(archivesManagerBeans);
        resultDTO.setMessage(I18nHelper.getMessage("CORE.MODULE.SYS.DPCONFIGS.TIP.IMPORT_SUCCESS"));
        return resultDTO;
    }

    @Override
    public boolean test(CoreFileBean coreFile, String service) {
        return true;
    }
}
